<template>
  <q-page class="q-pa-md">
    <div class="row q-gutter-md">
      <!-- 左侧控制面板 -->
      <div class="col-12 col-md-4">
        <q-card>
          <q-card-section>
            <div class="text-h6 q-mb-md">
              <q-icon name="view_in_ar" class="q-mr-sm" />
              NII文件加载器
            </div>
            
            <!-- 文件选择 -->
            <q-file
              v-model="selectedFile"
              label="选择NII文件"
              accept=".nii,.nii.gz"
              max-file-size="1000000000"
              @update:model-value="onFileSelected"
              class="q-mb-md"
            >
              <template v-slot:prepend>
                <q-icon name="psychology" />
              </template>
            </q-file>

            <!-- 预设文件 -->
            <div class="q-mb-md">
              <div class="text-subtitle2 q-mb-sm">预设示例文件：</div>
              <q-btn
                color="secondary"
                label="加载脑部MRI示例"
                @click="loadSampleNii"
                :loading="loading"
                class="full-width q-mb-xs"
              />
              <q-btn
                color="accent"
                label="加载功能性MRI示例"
                @click="loadFunctionalMri"
                :loading="loading"
                class="full-width"
              />
            </div>

            <!-- 文件信息 -->
            <q-card v-if="niiInfo" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">NII文件信息</div>
                <q-list dense>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>文件名</q-item-label>
                      <q-item-label>{{ niiInfo.fileName }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>数据类型</q-item-label>
                      <q-item-label>{{ niiInfo.dataType }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>维度</q-item-label>
                      <q-item-label>{{ niiInfo.dimensions }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>体素大小</q-item-label>
                      <q-item-label>{{ niiInfo.voxelSize }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>数据范围</q-item-label>
                      <q-item-label>{{ niiInfo.dataRange }}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-card-section>
            </q-card>

            <!-- 视图控制 -->
            <q-card v-if="imageLoaded" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">视图控制</div>
                
                <!-- 切片方向选择 -->
                <div class="q-mb-md">
                  <div class="text-caption q-mb-xs">切片方向</div>
                  <q-btn-toggle
                    v-model="sliceOrientation"
                    toggle-color="primary"
                    :options="[
                      {label: '轴位', value: 'axial'},
                      {label: '冠状', value: 'coronal'},
                      {label: '矢状', value: 'sagittal'}
                    ]"
                    @update:model-value="changeOrientation"
                    class="full-width"
                  />
                </div>

                <!-- 切片位置 -->
                <div class="q-mb-md">
                  <div class="text-caption q-mb-xs">
                    切片位置: {{ currentSlice }} / {{ maxSlice }}
                  </div>
                  <q-slider
                    v-model="currentSlice"
                    :min="0"
                    :max="maxSlice"
                    :step="1"
                    label
                    @update:model-value="updateSlice"
                  />
                </div>

                <!-- 颜色映射 -->
                <div class="q-mb-md">
                  <div class="text-caption q-mb-xs">颜色映射</div>
                  <q-select
                    v-model="colorMap"
                    :options="colorMapOptions"
                    @update:model-value="updateColorMap"
                    class="full-width"
                  />
                </div>

                <!-- 强度调整 -->
                <div class="q-mb-md">
                  <div class="text-caption q-mb-xs">强度窗口</div>
                  <q-range
                    v-model="intensityRange"
                    :min="niiInfo?.minValue || 0"
                    :max="niiInfo?.maxValue || 1000"
                    label
                    @update:model-value="updateIntensity"
                  />
                </div>
              </q-card-section>
            </q-card>

            <!-- 3D渲染控制 -->
            <q-card v-if="imageLoaded" flat bordered>
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">3D渲染</div>
                
                <q-btn-group spread class="q-mb-md">
                  <q-btn
                    :color="renderMode === '2d' ? 'primary' : 'grey'"
                    label="2D视图"
                    @click="setRenderMode('2d')"
                  />
                  <q-btn
                    :color="renderMode === '3d' ? 'primary' : 'grey'"
                    label="3D渲染"
                    @click="setRenderMode('3d')"
                  />
                </q-btn-group>

                <div v-if="renderMode === '3d'">
                  <div class="q-mb-sm">
                    <div class="text-caption q-mb-xs">不透明度</div>
                    <q-slider
                      v-model="opacity"
                      :min="0"
                      :max="1"
                      :step="0.1"
                      label
                      @update:model-value="updateOpacity"
                    />
                  </div>

                  <q-btn-group spread>
                    <q-btn size="sm" color="info" icon="rotate_left" @click="rotateLeft" />
                    <q-btn size="sm" color="info" icon="rotate_right" @click="rotateRight" />
                    <q-btn size="sm" color="info" icon="refresh" @click="resetView" />
                  </q-btn-group>
                </div>
              </q-card-section>
            </q-card>
          </q-card-section>
        </q-card>
      </div>

      <!-- 右侧显示区域 -->
      <div class="col-12 col-md-8">
        <q-card style="height: 600px;">
          <q-card-section class="full-height">
            <div v-if="!imageLoaded" class="flex flex-center full-height">
              <div class="text-center">
                <q-icon name="psychology" size="64px" color="grey-5" class="q-mb-md" />
                <div class="text-h6 text-grey-6">请选择NII文件</div>
                <div class="text-body2 text-grey-5">支持 .nii 和 .nii.gz 格式</div>
                <div class="text-caption text-grey-4 q-mt-sm">
                  NIfTI (Neuroimaging Informatics Technology Initiative) 格式
                </div>
              </div>
            </div>
            
            <div v-else class="full-height">
              <!-- NII图像显示容器 -->
              <div
                ref="niiContainer"
                class="nii-viewer full-height"
                style="background: #000; position: relative;"
              >
                <div v-if="loading" class="flex flex-center full-height">
                  <q-spinner-cube color="secondary" size="40px" />
                </div>
                
                <!-- 图像信息叠加 -->
                <div class="image-overlay">
                  <div class="text-white text-caption">
                    {{ sliceOrientation.toUpperCase() }} - {{ currentSlice }}/{{ maxSlice }}
                  </div>
                  <div class="text-white text-caption">
                    {{ niiInfo?.fileName }}
                  </div>
                  <div class="text-white text-caption">
                    {{ renderMode.toUpperCase() }} 模式
                  </div>
                </div>

                <!-- 十字线 -->
                <div v-if="renderMode === '2d'" class="crosshair">
                  <div class="crosshair-h"></div>
                  <div class="crosshair-v"></div>
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 响应式数据
const selectedFile = ref<File | null>(null)
const loading = ref(false)
const imageLoaded = ref(false)
const niiContainer = ref<HTMLElement | null>(null)

// NII文件信息
const niiInfo = ref<{
  fileName: string
  dataType: string
  dimensions: string
  voxelSize: string
  dataRange: string
  minValue: number
  maxValue: number
} | null>(null)

// 视图控制
const sliceOrientation = ref('axial')
const currentSlice = ref(0)
const maxSlice = ref(100)
const renderMode = ref('2d')

// 显示参数
const colorMap = ref('grayscale')
const colorMapOptions = [
  { label: '灰度', value: 'grayscale' },
  { label: '热图', value: 'hot' },
  { label: '冷图', value: 'cool' },
  { label: '彩虹', value: 'rainbow' },
  { label: '骨骼', value: 'bone' }
]

const intensityRange = ref({ min: 0, max: 1000 })
const opacity = ref(0.8)

// 文件选择处理
const onFileSelected = async (file: File | null) => {
  if (!file) return
  
  loading.value = true
  try {
    await loadNiiFile(file)
  } catch (error) {
    console.error('加载NII文件失败:', error)
    $q.notify({
      type: 'negative',
      message: '加载NII文件失败',
      caption: '请检查文件格式是否正确'
    })
  } finally {
    loading.value = false
  }
}

// 加载示例NII文件
const loadSampleNii = async () => {
  loading.value = true
  try {
    // 模拟加载示例文件
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    niiInfo.value = {
      fileName: 'brain_mri_sample.nii.gz',
      dataType: 'int16',
      dimensions: '256 × 256 × 180',
      voxelSize: '1.0 × 1.0 × 1.0 mm',
      dataRange: '0 - 4095',
      minValue: 0,
      maxValue: 4095
    }
    
    maxSlice.value = 180
    currentSlice.value = 90
    intensityRange.value = { min: 0, max: 4095 }
    imageLoaded.value = true
    
    $q.notify({
      type: 'positive',
      message: 'NII文件加载成功',
      caption: '脑部MRI示例数据'
    })
  } catch (error) {
    console.error('加载示例文件失败:', error)
    $q.notify({
      type: 'negative',
      message: '加载示例文件失败'
    })
  } finally {
    loading.value = false
  }
}

// 加载功能性MRI示例
const loadFunctionalMri = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    niiInfo.value = {
      fileName: 'fmri_sample.nii.gz',
      dataType: 'float32',
      dimensions: '64 × 64 × 30 × 200',
      voxelSize: '3.0 × 3.0 × 4.0 mm',
      dataRange: '-10.5 - 15.8',
      minValue: -10.5,
      maxValue: 15.8
    }
    
    maxSlice.value = 30
    currentSlice.value = 15
    intensityRange.value = { min: -10.5, max: 15.8 }
    imageLoaded.value = true
    colorMap.value = 'hot'
    
    $q.notify({
      type: 'positive',
      message: 'fMRI文件加载成功',
      caption: '功能性磁共振成像数据'
    })
  } finally {
    loading.value = false
  }
}

// 加载NII文件的核心逻辑
const loadNiiFile = async (file: File) => {
  // 这里应该集成NIfTI.js或类似库来加载NII文件
  // 目前先模拟加载过程
  
  niiInfo.value = {
    fileName: file.name,
    dataType: 'int16',
    dimensions: '256 × 256 × 128',
    voxelSize: '1.0 × 1.0 × 1.0 mm',
    dataRange: '0 - 2048',
    minValue: 0,
    maxValue: 2048
  }
  
  maxSlice.value = 128
  currentSlice.value = 64
  intensityRange.value = { min: 0, max: 2048 }
  
  // 模拟加载延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  imageLoaded.value = true
  
  $q.notify({
    type: 'positive',
    message: 'NII文件加载成功',
    caption: `已加载: ${file.name}`
  })
}

// 切换切片方向
const changeOrientation = (orientation: string) => {
  console.log('切换到', orientation, '方向')
  // 根据方向调整最大切片数
  switch (orientation) {
    case 'axial':
      maxSlice.value = 128
      currentSlice.value = 64
      break
    case 'coronal':
      maxSlice.value = 256
      currentSlice.value = 128
      break
    case 'sagittal':
      maxSlice.value = 256
      currentSlice.value = 128
      break
  }
}

// 更新切片位置
const updateSlice = (slice: number) => {
  console.log('切换到切片:', slice)
  // 这里应该调用NII查看器的切片更新功能
}

// 更新颜色映射
const updateColorMap = (colormap: string) => {
  console.log('更新颜色映射:', colormap)
}

// 更新强度范围
const updateIntensity = (range: { min: number, max: number }) => {
  console.log('更新强度范围:', range)
}

// 设置渲染模式
const setRenderMode = (mode: string) => {
  renderMode.value = mode
  console.log('切换渲染模式:', mode)
}

// 更新不透明度
const updateOpacity = (value: number) => {
  console.log('更新不透明度:', value)
}

// 3D控制
const rotateLeft = () => {
  console.log('向左旋转')
}

const rotateRight = () => {
  console.log('向右旋转')
}

const resetView = () => {
  console.log('重置视图')
  currentSlice.value = Math.floor(maxSlice.value / 2)
  opacity.value = 0.8
}

onMounted(() => {
  console.log('初始化NII查看器')
})

onUnmounted(() => {
  console.log('清理NII查看器资源')
})
</script>

<style scoped>
.nii-viewer {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.image-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.8);
  padding: 8px 12px;
  border-radius: 4px;
  z-index: 10;
}

.crosshair {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 5;
}

.crosshair-h {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: rgba(255, 255, 0, 0.7);
  transform: translateY(-50%);
}

.crosshair-v {
  position: absolute;
  left: 50%;
  top: 0;
  bottom: 0;
  width: 1px;
  background: rgba(255, 255, 0, 0.7);
  transform: translateX(-50%);
}

.full-height {
  height: 100%;
}
</style>

